package com.shusl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
//SpringSecurity 新版2.7+
@Configuration
@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig  {
    /**
     * 授权
     * @return
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 定制请求的授权规则
        // 首页所有人可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //防止网站工具：get post
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求

        // 开启自动配置的登录功能
        // loginPage("/toLogin")定制登录首页 .usernameParameter("user")定制用户参数.passwordParameter()定制密码参数
        http.formLogin().loginPage("/toLogin");
        //开启自动配置的注销的功能logout 注销请求
        http.logout();
        //记住我rememberMeParameter设置参数
        http.rememberMe().rememberMeParameter("remeberMe");
        return http.build();
    }

    /**
     * 认证
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService() {
        //在内存中定义，也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式，也改变了密码的格式。
        //要想我们的项目还能够正常登陆，需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。

        //密码加密
        PasswordEncoder encoder= PasswordEncoderFactories.createDelegatingPasswordEncoder();
        //设置用户
        UserDetails user1 = User.builder()
                .username("lailai")
                .password(encoder.encode("123456"))
                //用户权限
                .roles("vip1")
                .build();

        UserDetails user2=User.builder()
                .username("root")
                .password(encoder.encode("123456"))
                .roles("vip1","vip2","vip3")
                .build();

        return new InMemoryUserDetailsManager(user1,user2);
    }


}
